package baseconfig

import (
	"fmt"
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/base/baseutils/jsonutils"
	"os"
	"strings"
)

/*
@Title    文件名称: configitem.go
@Description  描述: 配置项解析值

@Author  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
@Update  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
*/
type ConfigItem struct {
	//键值
	Key string `json:"key"`
	//配置值
	Value string `json:" "`
	// 环境变量
	EnvValue string `json:"env_value"`
	// 默认值
	DefaultValue string `json:"default_value"`
	// 实际值
	EndValue string `json:"end_value"`

	basedto.BaseEntity
}

func NewConfigItem(k, v string) *ConfigItem {
	var item = &ConfigItem{
		Key:   k,
		Value: v,
	}
	item.InitProxy(item)
	return item
}

func (this *ConfigItem) Check() bool {
	var has = strings.HasPrefix(this.Value, "${")
	if !has {
		return true
	}
	return strings.HasPrefix(this.Value, "}")
}

// ${HOSTURL:huawei.akunlong.top:2379}
func (this *ConfigItem) ParseValue() *ConfigItem {
	if strings.Contains(this.Value, "${") {
		this.parseEnv()
	} else {
		this.defaultValue()
	}
	return this
}
func (this *ConfigItem) parseEnv() *ConfigItem {
	var strs = strings.Split(this.Value, ":")

	fmt.Println(strs)
	this.EnvValue = strings.Split(strs[0], "{")[1]

	var start = strings.Index(this.Value, ":") + 1
	var end = len(this.Value) - 1
	this.DefaultValue = this.Value[start:end] //this.Value
	if os.Getenv(this.EnvValue) != "" {
		this.EndValue = os.Getenv(this.EnvValue)

	} else {
		this.EndValue = this.DefaultValue
	}

	return this
}
func (this *ConfigItem) defaultValue() *ConfigItem {
	this.EnvValue = ""
	this.DefaultValue = this.Value
	this.EndValue = this.Value
	return this
}

func (this *ConfigItem) String() string {
	return jsonutils.ToJsonPretty(this)
}
func (this *ConfigItem) Log() {
	fmt.Println(this.String())
}
